<template>
  <div class="container-fluid">
    <div class="todos">
      <h3 class="todo-header">Todo示例</h3>
      <create-form @addItem="handleAddItem"></create-form>
      <div v-for="(todo, index) in todoList" :key="index">
        <todo-item
          @deleteTodo="handleDelete"
          @editTodo="handleEdit"
          @editFinish="handleFinish"
          :todo="todo"
          v-if="!todo.isEditable"
        >
        </todo-item>
        <edit-todo :todo="todo" :key="index" @editItem="handleEditTodo" v-else></edit-todo>
      </div>
    </div>
  </div>
</template>

<script>
import CreateForm from './CreateForm.vue'
import TodoItem from './Todo.vue'
import EditTodo from './EditTodo.vue'
export default {
  data() {
    return {
      todoList: [],
    }
  },
  components: {
    CreateForm,
    TodoItem,
    EditTodo,
  },
  methods: {
    handleAddItem(content) {
      console.log(content)
      this.todoList.push({
        id: this.todoList.length + 1,
        content: content,
        isFinished: false,
        isEditable: false,
      })
    },
    handleDelete(id) {
      //根据todo对象的id找到它在数组中的位置,使用splice进行删除
      const index = this.todoList.findIndex((item) => item, id == id)
      this.todoList.splice(index, 1)
    },
    handleEdit(id) {
      //找到id：id的todo，修改isEditable为true
      this.todoList.find((todo) => todo.id == id).isEditable = true
    },
    handleEditTodo(id, content) {
      console.log(id, content)
      //根据id找到todo对象
      const todo = this.todoList.find((todo) => todo.id == id)
      //修改todo内容
      todo.content = content
      //修改isEditable为false
      todo.isEditable = false
    },
    handleFinish(id) {
      const todo = this.todoList.find((todo) => todo.id == id)
      //当用户点击todo内容时，如果isFinished为flase，则修改为true，反之，则修改为flase
      todo.isFinished = !todo.isFinished
    },
  },
}
</script>

<style lang="scss" scoped>
.container-fluid {
  width: 100%;
  height: 100vh;
  background: #3b36cc;
  display: flex;
  justify-content: center;
  color: white;
}
.todos {
  width: 450px;
  background-color: #1a1a40;
  padding: 20px;
}
.todos > h3 {
  text-align: center;
  margin-top: 20px;
}
</style>
